import { defineStore } from 'pinia'
import { clearAppInfo, APPINFO_KEY } from '@/utils/auth'
import { getUserInfo, getMenuList } from '@/api/public'
import { login as userLogin, logout as userLogout } from '@/api/login'
import { HOME } from '@/router/constants'
import clientRoutes from '@/router/appRoutes'
import piniaPersistConfig from '@/hooks/piniaPersist'
import golbalSettings from '@/config/settings.json'

const useAppStore = defineStore('app', {
  state: (): API.AppState => ({
    token: <string>'',
    isAuthenticated: false,
    userInfo: <API.UserInfo>{},
    roles: <string[]>[],
    permissions: <string[]>[],
    menuList: <API.MenuListItem[]>[],

    golbalSettings: { ...golbalSettings }
  }),

  actions: {
    /** 设置token */
    setToken(token: string) {
      this.token = token
      if (this.token !== '') this.isAuthenticated = true
    },

    /** 设置用户信息 */
    setUserInfo(userInfo: API.UserInfo) {
      this.userInfo = userInfo
    },

    /** 换肤 */
    switchTheme(isDark: boolean) {
      this.golbalSettings.isDark = isDark
      this.golbalSettings.theme = isDark ? 'dark' : 'light'
    },

    /** 切换侧边栏 */
    switchAsideMenu() {
      this.golbalSettings.menuCollapse = !this.golbalSettings.menuCollapse
    },

    /** 重置state */
    reset() {
      this.$reset()
    },

    /** 清空本地存储信息 */
    clearLocalInfo() {
      clearAppInfo()
    },

    /** 获取用户信息 */
    async fetchUserInfos() {
      const res: API.UserInfoResult = await getUserInfo()
      if (res.code === 200) {
        const { permissions, roles, user } = res
        this.permissions = permissions
        this.roles = roles
        this.userInfo = { ...user }
      }
    },

    /** 获取用户权限菜单列表 */
    async fetchUserMenuList() {
      const res = await getMenuList()
      if (res.code === 200) {
        res.data.forEach((item) => {
          if (item.component === 'Layout' && item?.children?.length) {
            item.children.forEach((key) => {
              key.component = `@/view/${key.component}`
              return key
            })
          }
          return item
        })

        this.menuList = this.golbalSettings.menuFromServer
          ? [HOME, ...res.data]
          : [...(clientRoutes as unknown as API.MenuListItem[])]
      }
    },

    /** 登录 */
    async login(loginParams: API.LoginParams) {
      try {
        const res: API.LoginResult = await userLogin(loginParams)
        if (res.code === 200) {
          this.setToken(res.token)
          return res
        }
      } catch (err) {
        this.reset()
        throw err
      }
    },

    /** 退出登录 */
    async logout() {
      await userLogout()
      this.reset()
      this.clearLocalInfo()
    }
  },

  /** 数据持久化 */
  persist: piniaPersistConfig(APPINFO_KEY)
})

export default useAppStore
